import Vue from "vue";

export default ({ app, $axios }, inject) => {
    const OssHandel = {
        loading: false,
        callback: [],
        client: null,
        timer: 0,
    };

    // 选择文件
    Vue.prototype.$selectFile = () => {
        return new Promise((resolve, reject) => {
            let filebox = document.querySelector(".filebox");
            let input = null;

            if (filebox) {
                input = filebox.querySelector("input");
            } else {
                filebox = document.createElement("div");
                filebox.setAttribute("class", "filebox");
                filebox.setAttribute(
                    "style",
                    " position: absolute;left: 0;top: 0;width: 0;height: 0;overflow: hidden;opacity: 0;"
                );
                filebox.innerHTML =
                    '<input type="file" accept="image/jpeg,image/jpg,image/png">';
                document.body.appendChild(filebox);
                input = filebox.querySelector("input");
            }

            // const focusEvent = (event) => {
            // 	// 有可能有延时
            // 	window.removeEventListener('focus', focusEvent)
            // 	setTimeout(() => {
            // 		if (!input.lock) {
            // 			reject('Selected cancel', input.files.length)
            // 			// document.getElementById(input.id) && input.remove();
            // 		} else {
            // 			// input.remove();
            // 		}
            // 	}, 500)
            // }

            input.onchange = () => {
                if (input.files && input.files[0]) {
                    option.file = input.files[0];
                    let maxsize = 1024 * 1024 * 50; // 不能上传超过50M的图片
                    if (option.file.size > maxsize) {
                        // 图片过大
                        const notify = "The maximum upload file size is 50M.";
                        this.$uxMessage.error(notify);
                        reject(notify);
                    } else {
                        resolve(option);
                    }
                } else {
                    reject("No file select");
                }
                input.lock = true;
                input.value = null;
                filebox.remove();
                // filebox.innerHTML = html;
            };

            // window.addEventListener('focus', focusEvent)
            input.click();
        });
    };

    // 上传画布
    Vue.prototype.$uploadCanvas = (canvas, spu) => {
        // let test = function(canvas){
        //   let div = document.querySelector('.test');
        //   if(!div){
        //     div = document.createElement('div');
        //     div.style.cssText = 'display:flex;flex-wrap:wrap; position: absolute;left: 0;top: 0;height:200px;z-index:9999;';
        //     div.setAttribute('class','test')
        //     document.body.appendChild(div);
        //   }

        //   let image = new Image();
        //   image.src = canvas.toDataURL({format: "png"});
        //   image.style.width = 'auto';
        //   image.style.height = '100%';
        //   image.style.border = '1px solid #f00';
        //   div.appendChild(image);
        // }
        // test(canvas);

        // return new Promise((resolve, reject) => {
        //   resolve({data:'/data/pod/file/b2e2bf28d875edaf6caf64e330511d21/956ea7d2-4612-4393-8f3d-7bd4bcfc3c2a.png',name:canvas.name || ''});
        // })

        return new Promise((resolve, reject) => {
            try {
                canvas.toBlob(
                    (blob) => {
                        let filename = canvas.name;
                        if (!filename) {
                            let time = new Date().getTime();
                            let random = Math.random().toFixed(10).substr(2);
                            filename = "canvas-" + time + "-" + random + ".png";
                        }

                        let option = {
                            spu: spu,
                            file: blob,
                            name: filename,
                        };

                        Vue.prototype
                            .$uploadFile(option)
                            .then(resolve)
                            .catch(reject);
                    },
                    "image/png",
                    1
                );
            } catch (error) {
                reject(error);
            }
        });
    };

    Vue.prototype.$uploadToOSS = (option, callback) => {
        let time = new Date().getTime();

        // 上传
        let doUpload = (client, option, callback) => {
            let name = option.path + option.name;
            let onprogress = option.onprogress;

            // 上传断网的时候，会等得特别久
            client
                .multipartUpload(name, option.file, {
                    parallel: 2,
                    headers: { Expires: "108000000" }, // 指定过期时间，单位为毫秒。
                    progress: (per, cpt) => {
                        let percent = Math.floor(100 * per);
                        onprogress &&
                            onprogress({
                                code: 100,
                                msg: "Image is being uploaded",
                                percent: percent,
                                cpt: cpt,
                                client: client,
                            });

                        // 取消
                        // client.abortMultipartUpload(cpt.name, cpt.uploadId)
                    },
                })
                .then((result) => {
                    callback &&
                        callback({
                            code: 0,
                            msg: "Image uploaded!",
                            data: result.name,
                        });
                })
                .catch((err) => {
                    // 失败
                    callback && callback({ code: 400, msg: "Upload failed!" });
                });
        };

        // ossLasTime
        // 5分钟内
        if (OssHandel.client && time - OssHandel.time < 300000) {
            doUpload(OssHandel.client, option, callback);
        } else if (OssHandel.loading) {
            OssHandel.callback.push({ option: option, callback: callback });
        } else {
            // let test = {AccessKeySecret:"DGK2dU1v6ogTZWQDrQKRdK88i1P5ZNhVGTv2FYNRD9tH", Expiration:"2022-01-22T09:48:58Z", AccessKeyId:"STS.NSqpSAeoo7PXZyJSMidYKGf3h", SecurityToken:"CAIS6AF1q6Ft5B2yfSjIr5DEO+n1iLBOgJKzWF/7t008aNZnqKOYijz2IH5MfXZpAesWsvU3mmxZ7fcZlq9+UZlETEuc4GbZDxQQo22beIPkl5Gfz95t0e+IewW6Dxr8w7WhAYHQR8/cffGAck3NkjQJr5LxaTSlWS7OU/TL8+kFCO4aRQ6ldzFLKc5LLw950q8gOGDWKOymP2yB4AOSLjIx51Yi1jgutPnmmZDNtkWBtjCglL9J/baWC4O/csxhMK14V9qIx+FsfsLDqnUOs0EVrf8t3PAVoWmb74rMWEM6/BiMI3cfCVmCnLgTGoABcFf5/VBX1HM4xfKpmQrM+Hkt26tXyc95Jih1AusO6UY9+AysXxgBE/fjTujZo3Hb6SRYLjSx9dZpKo1D0vANqTXAOTIlR7qvEYt6ytxe8ZymZeWT4XTJYFnByftg8NM8UtlrALwKbSjm6wJQHNJVI78+2uJGfr2wQaGakUugit8="}
            // ossClient = new OSS({
            //   accessKeyId: test.AccessKeyId,
            //   accessKeySecret: test.AccessKeySecret,
            //   stsToken: test.SecurityToken,
            //   region: 'oss-accelerate',
            //   bucket: 'pod-product-cn', // 填写Bucket名称。
            //   secure: true,

            //   // region: 'oss-cn-shenzhen',
            //   // endpoint: 'http://cn-shenzhen.aliyuncs.com'
            // });

            OssHandel.loading = true;
            OssHandel.callback.push({ option: option, callback: callback });

            Promise.all([import("ali-oss"), Vue.prototype.$http("ossUpload")])
                .then((result) => {
                    let OSS = (result[0] || {}).default;
                    let response = result[1] || {};
                    if (OSS && response.code == 0) {
                        let data = response.data;
                        let config = {
                            accessKeyId: data.AccessKeyId,
                            accessKeySecret: data.AccessKeySecret,
                            stsToken: data.StsToken,
                            region: data.Region,
                            bucket: data.Bucket, // 填写Bucket名称。
                            secure: true,

                            // region: 'oss-cn-shenzhen',
                            // endpoint: 'http://cn-shenzhen.aliyuncs.com'
                        };

                        OssHandel.client = new OSS(config);
                        OssHandel.loading = false;
                        OssHandel.timer = new Date().getTime();
                        OssHandel.callback.map((opt) =>
                            doUpload(OssHandel.client, opt.option, opt.callback)
                        );
                        OssHandel.callback = [];

                        // doUpload(OssHandel.client,option,callback)
                    } else {
                        // callback && callback({code:400,msg:'Failed to get signature'});
                        OssHandel.callback.map(
                            (opt) =>
                                opt.callback &&
                                opt.callback({
                                    code: 400,
                                    msg: "Failed to get signature",
                                })
                        );
                        OssHandel.callback = [];
                        OssHandel.loading = false;
                    }
                })
                .catch((error) => {
                    OssHandel.callback.map(
                        (opt) =>
                            opt.callback &&
                            opt.callback({
                                code: 400,
                                msg: "Failed to get signature",
                            })
                    );
                    OssHandel.callback = [];
                    OssHandel.loading = false;
                });
        }
    };

    // 上传文件
    Vue.prototype.$uploadFile = (request = {}) => {
        // 上传功能
        let uploadFile;

        // 上传数据
        let option = {
            file: request.file,
            filename: request.name || request.file.name,
            onprogress: request.onprogress,
            other: {},
        };

        // 获取其他数据
        Object.keys(request).map((key) => {
            let names = ["url", "file", "name", "onprogress"];
            if (names.indexOf(key) < 0) {
                option.other[key] = request[key];
            } else {
                // 不用传的参数
            }
        });

        if (option.other.path) {
            // 阿里云上传
            uploadFile = Vue.prototype.$uploadToOSS;
        } else {
            // 图片上传
            uploadFile = (option, callback) => {
                let form = new FormData();
                let token = app.store.getters["getToken"];
                let xhr = new XMLHttpRequest();
                let url = (
                    Vue.prototype.$getApi("Material.postMaterialFile") || {}
                ).url;

                form.append("file", option.file, option.filename);

                for (let key in option.other) {
                    form.append(key, option.other[key]);
                }

                xhr.timeout = 108000000; // 超时时间，单位是毫秒
                xhr.open("post", DOMAIN_API + url, true);

                xhr.setRequestHeader("Authorization", `Bearer ${token}`);
                xhr.onload = (event) => {
                    if (xhr.status == 200) {
                        let json;
                        try {
                            json = JSON.parse(xhr.responseText);
                        } catch (e) {
                            json = {};
                        }
                        callback(json);
                    } else {
                        callback({ code: 400, msg: "Server status abnormal" });
                    }
                };
                xhr.ontimeout = (event) => {
                    callback({ code: 400, msg: "Connect time out" });
                };
                xhr.onerror = (event) => {
                    callback({ code: 400, msg: "Upload failed!" });
                };

                // 获取上传进度
                if (option.onprogress) {
                    xhr.upload.onprogress = (event) => {
                        if (event.lengthComputable) {
                            let percent = Math.floor(
                                (event.loaded / event.total) * 100
                            );
                            let progress = {
                                percent: percent,
                                total: event.total,
                                loaded: event.loaded,
                            };
                            option.onprogress && option.onprogress(progress);
                        }
                    };
                }

                xhr.send(form);
            };
        }

        return new Promise((resolve, reject) => {
            if (option.file) {
                uploadFile(option, resolve);
            } else {
                reject({ code: 400, msg: "Image not found" });
            }
        });
    };
};
